// 防抖
const vDebounce = {
  name: 'debounce',
  mounted: (el, binding) => {
    let timer = 0

    el.addEventListener('click', (e) => {
      // 阻止默认事件
      e.preventDefault()
      // 阻止冒泡
      e.stopPropagation()

      if (timer) {
        clearTimeout(timer)
      }

      let delay = binding.value?.delay || 1000
      timer = setTimeout(() => {
        const { callback, params } = binding.value
        // callback 不是函数
        if (!callback || typeof callback !== 'function') {
          throw new Error('callback is not a function')
        }
        callback(params ? params : e)
        //重置定时器
        timer = null
      }, delay)
    })
  },
}

export default vDebounce
